package reflect;

import reflect.annotation.AutoRunClass;
import reflect.annotation.AutoRunMethod;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
 * 调用与当前类Test6在同一个包中被注解@AutoRunClass标注的类中那些被注解@AutoRunMethod标注的方法若干次(次数由该方法注解的参数确定)
 */

public class Test6 {
    public static void main(String[] args) throws URISyntaxException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
        //获取当前类所在的路径
        File dir=new File(Test6.class.getResource(".").toURI());
        //获取当前类包名
        String packName=Test6.class.getPackage().getName();
        //获取当前类所在的路径下的所有.class文件
        File[] files=dir.listFiles(f->f.getName().endsWith(".class"));
        for (File file:files){
            String fileName=file.getName();
            String className=fileName.substring(0,fileName.indexOf("."));
            Class cls=Class.forName(packName+"."+className);
            if (cls.isAnnotationPresent(AutoRunClass.class)){
                Object obj=cls.newInstance();
                Method[] methods=cls.getDeclaredMethods();
                for (Method method:methods){
                    if (method.isAnnotationPresent(AutoRunMethod.class)){
                       AutoRunMethod arm= method.getAnnotation(AutoRunMethod.class);
                      int value= arm.value();
                        System.out.println("开始调用"+method.getName()+value+"次");
                      for(int i=0;i<value;i++){
                          method.invoke(obj);
                      }
                    }
                }
            }

        }



    }
}
